#/usr/bin/bash
INSTALL_PATH=$1
if [ ! $INSTALL_PATH ];then
	INSTALL_PATH="/usr/local/maven"
fi

#Maven架包下载路径,不传默认ftp://ftpUser:123456@175.178.190.189/maven/maven-3.8.5/apache-maven-3.8.5-bin.tar.gz
DOWNLOAD_URL=$2
if [ ! $DOWNLOAD_URL ];then
DOWNLOAD_URL="ftp://ftpUser:123456@175.178.190.189/maven/maven-3.8.5/apache-maven-3.8.5-bin.tar.gz"
fi

MAVEN_WAREHOUSE=$3

#如果文件夹不存在，创建文件夹
if [ ! -d $INSTALL_PATH ];then
   mkdir $INSTALL_PATH
fi

cd $INSTALL_PATH

#wget下载文件
wget $DOWNLOAD_URL

##获取文件名
FILENAME=${DOWNLOAD_URL##*/};

#判断当前文件是什么压缩包
if [ ${FILENAME##*.} = gz ];then
  TEMP=${FILENAME%.*}
    if [ ${TEMP##*.} = tar ];then
        tar -zxvf $FILENAME -C $INSTALL_PATH
    else
        unzip  $FILENAME -d  $INSTALL_PATH
    fi
elif [ ${FILENAME##*.} = zip ];then
    unzip  $FILENAME -d  $INSTALL_PATH
fi


#删除安装包
rm -rf $INSTALL_PATH/$FILENAME

#获取解压后当前目录下的文件名
NEW_FILENAME=`ls -lt $INSTALLPATH |grep maven|head -n 1|awk '{print $9}'`;

if [ ! $NEW_FILENAME ];then
  echo "解压失败，获取不到解压后的文件名，退出脚本";
  exit
fi

if [ ! $MAVEN_WAREHOUSE ];then
        MAVEN_WAREHOUSE="$INSTALL_PATH/$NEW_FILENAME/repo"
fi


if [ ! -d $MAVEN_WAREHOUSE ];then
	mkdir $MAVEN_WAREHOUSE
fi

cd $INSTALL_PATH/$NEW_FILENAME/conf

#做个备份
cp settings.xml setting_backups.xml

sed -i "/^.*<!--.* localRepository.*$/i <localRepository>$MAVEN_WAREHOUSE<\/localRepository>" settings.xml

sed -i "/^.*<\/mirror>.*$/a <mirror>\n<id>alimaven<\/id>\n<name>aliyun maven</name>\n<url>http\:\//maven.aliyun.com\/nexus\/content\/groups\/public\/<\/url>\n<mirrorOf>central<\/mirrorOf>\n<\/mirror>\n" settings.xml

#在DOS/Windows里，文本文件的换行符为\r\n，而在nix系统里则为\n，所以DOS/Windows里编辑过的文本文件到了nix里，每一行都多了个^M
#这里去除^M
sed -i "s/\r//" settings.xml



cd /etc/profile.d/


#创建maven_env.sh文件并配置环境变量
#先判断文件是否已经存在，若存在先删除
if [ -f maven_env.sh ];then
	rm -rf maven_env.sh;
fi

#配置Maven环境变量
cat >>/etc/profile.d/maven_env.sh<<EOF 
export MAVEN_HOME=$INSTALL_PATH/$NEW_FILENAME
export PATH=\$PATH:\$MAVEN_HOME/bin
EOF

#重启/ect/profile环境
source /etc/profile


#验证是否安装jdk完毕
mvn -v

if [ $? -ne 0 ];then
        echo "-----------------------maven安装失败，请排查!!!，退出脚本----------------------";
        exit;
else
	echo "-----------------------maven安装成功，即将退出脚本----------------------";
fi
